package org.jeecg.modules.api.member.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.system.vo.MemberModel;
import org.jeecg.config.app.AppContext;
import org.jeecg.modules.api.member.entity.Member;
import org.jeecg.modules.api.member.service.IMemberService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.helper.MemberHelp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @Description: 用户分销信息
 * @Author: jeecg-boot
 * @Date: 2024-09-19
 * @Version: V1.0
 */
@Api(tags = "用户分销信息")
@RestController
@RequestMapping("/member")
@Slf4j
public class MemberController extends JeecgController<Member, IMemberService> {
    @Autowired
    private IMemberService userinfoService;
    @Autowired
    private MemberHelp memberHelp;

    /**
     * 分页列表查询
     *
     * @param member
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "用户分销信息-分页列表查询")
    @ApiOperation(value = "用户分销信息-分页列表查询", notes = "用户分销信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<Member>> queryPageList(Member member,
                                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                               HttpServletRequest req) {
        // 自定义查询规则
        Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
        // 自定义多选的查询规则为：LIKE_WITH_OR
        customeRuleMap.put("level", QueryRuleEnum.LIKE_WITH_OR);
        String userPhone = req.getParameter("userPhone");
        String recPhone = req.getParameter("recPhone");

        QueryWrapper<Member> queryWrapper = QueryGenerator.initQueryWrapper(member, req.getParameterMap(), customeRuleMap);
        if(StringUtils.isNotEmpty(userPhone)){
            queryWrapper.or().eq("phone",userPhone);
            queryWrapper.or().eq("nickname",userPhone);
        }
        if(StringUtils.isNotEmpty(recPhone)){
            queryWrapper.or().eq("phone",recPhone);
            queryWrapper.or().eq("nickname",recPhone);
        }
        Page<Member> page = new Page<Member>(pageNo, pageSize);
        IPage<Member> pageList = userinfoService.page(page, queryWrapper);
        for (Member record : pageList.getRecords()) {
            List<Member> myTeams = getMyTeam(record.getId());
            record.setChildList(myTeams);
            Member rec= userinfoService.getById(record.getRecommendId());
            record.setRecommend(rec);
            memberHelp.setMemberExtension(record);
        }
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param member
     * @return
     */
    @AutoLog(value = "用户分销信息-添加")
    @ApiOperation(value = "用户分销信息-添加", notes = "用户分销信息-添加")
    @RequiresPermissions("member:member:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody Member member) {
        userinfoService.save(member);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param member
     * @return
     */
    @AutoLog(value = "用户分销信息-编辑")
    @ApiOperation(value = "用户分销信息-编辑", notes = "用户分销信息-编辑")
    @RequiresPermissions("member:member:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody Member member) {
        userinfoService.updateById(member);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "用户分销信息-通过id删除")
    @ApiOperation(value = "用户分销信息-通过id删除", notes = "用户分销信息-通过id删除")
    @RequiresPermissions("member:member:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        userinfoService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "用户分销信息-批量删除")
    @ApiOperation(value = "用户分销信息-批量删除", notes = "用户分销信息-批量删除")
    @RequiresPermissions("member:member:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.userinfoService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "用户分销信息-通过id查询")
    @ApiOperation(value = "用户分销信息-通过id查询", notes = "用户分销信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<Member> queryById(@RequestParam(name = "id", required = true) String id) {
        Member member = userinfoService.getById(id);
        if (member == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(member);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param member
     */
    @RequiresPermissions("member:member:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Member member) {
        return super.exportXls(request, member, Member.class, "用户分销信息");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("member:member:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Member.class);
    }
    public List<Member> getMyTeam(Long memberId) {
        if (memberId == null) {
            MemberModel memberModel = AppContext.get();
            memberId = memberModel.getId();
        }
        List<Member> list = userinfoService.list(new LambdaQueryWrapper<Member>().eq(Member::getRecommendId, memberId));
        for (Member m : list) {
            List<Member> childTeamList = userinfoService.list(new LambdaQueryWrapper<Member>().in(Member::getRecommendId, m.getId()));
            m.setChildList(childTeamList);
        }
        return list;
    }
}
